//
//  SPEditViewController.m
//  Sport
//
//  Created by Cass on 2017/12/3.
//  Copyright © 2017年 Cass. All rights reserved.
//

#import "SPEditViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "SPUserInfo.h"
@interface SPEditViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIPickerViewDelegate,UIPickerViewDataSource>
@property (weak, nonatomic) IBOutlet UIView *iconView;
@property (weak, nonatomic) IBOutlet UIImageView *iconImg;
@property (weak, nonatomic) IBOutlet UIButton *iconBtn;
@property (weak, nonatomic) IBOutlet UITextField *nameText;
@property (weak, nonatomic) IBOutlet UITextField *persignatureText;
@property (weak, nonatomic) IBOutlet UILabel *genderText;
@property (weak, nonatomic) IBOutlet UILabel *ageText;
@property (weak, nonatomic) IBOutlet UILabel *hobbyText;
@property (weak, nonatomic) IBOutlet UILabel *locationText;
@property (weak, nonatomic) IBOutlet UILabel *occupationText;
@property (nonatomic, strong) UIPickerView *sexPicker;
@property (nonatomic, strong) UIPickerView *agePicker;
@property (nonatomic, strong) UIPickerView *hobbyPicker;
@property (nonatomic, strong) UIPickerView *locationPicker;
@property (nonatomic, strong) UIPickerView *occupationPicker;

@property (nonatomic, strong) SPUserInfo *userInfo;
@property (nonatomic, strong) NSArray *sexArr;
@property (nonatomic, strong) NSMutableArray *ageArr;
@property (nonatomic, strong) NSArray *hobbyArr;
@property (nonatomic, strong) NSArray *locationArr;
@property (nonatomic, strong) NSArray *occupationArr;

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIView *BGView;

@property (nonatomic,copy) NSString *ID;
@end

@implementation SPEditViewController

- (NSArray *)occupationArr{
    if (!_occupationArr) {
        _occupationArr = [[NSArray alloc]initWithObjects:@"白领",@"IT",@"教师",@"运动员",@"学生", nil];
    }
    return _occupationArr;
}
- (NSArray *)locationArr{
    if (!_locationArr) {
        _locationArr = [[NSArray alloc]initWithObjects:@"成都",@"上海",@"北京",@"深圳",@"广东",@"重庆", nil];
    }
    return _locationArr;
}
- (NSArray *)hobbyArr{
    if (!_hobbyArr) {
        _hobbyArr = [[NSArray alloc]initWithObjects:@"足球",@"篮球",@"羽毛球",@"乒乓球",@"网球", nil];
    }
    return _hobbyArr;
}
- (NSMutableArray *)ageArr{
    if (!_ageArr) {
        _ageArr = [[NSMutableArray alloc]init];
        for (int i = 0; i < 100; i++) {
            NSString *number = [NSString stringWithFormat:@"%d",i];
            [_ageArr addObject:number];
        }
    }
    return _ageArr;
}
- (SPUserInfo *)userInfo{
    if (!_userInfo) {
        _userInfo = [[SPUserInfo alloc]init];
        //读取账户信息
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        _userInfo.headimage = [userDefault objectForKey:@"headimage"];
        _userInfo.nickname = [userDefault objectForKey:@"nickname"];
        _userInfo.gender = [userDefault objectForKey:@"gender"];
        _userInfo.age = [userDefault objectForKey:@"age"];
        _userInfo.hobby = [userDefault objectForKey:@"hobby"];
        _userInfo.location = [userDefault objectForKey:@"location"];
        _userInfo.occupation = [userDefault objectForKey:@"occupation"];
        _userInfo.persignature = [userDefault objectForKey:@"persignature"];
    }
    return _userInfo;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //读取账户ID号
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    self.ID = [userDefault objectForKey:@"ID"];
    [self setBasicInfo];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.iconImg.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(alertAction)];
    [self.iconImg addGestureRecognizer:tap];
    [self.iconView bringSubviewToFront:self.iconImg];
    [self setPicker];
    [self configuration];
}

- (void)configuration{
    UIBarButtonItem *rightItem = [UIBarButtonItem itemWithImage:@"" selectedImage:@"" title:@"保存" target:self action:@selector(save)];
    self.navigationItem.rightBarButtonItem = rightItem;
}
- (void)save{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setObject:self.nameText.text forKey:@"nickname"];
    [userDefault setObject:self.ageText.text forKey:@"age"];
    [userDefault setObject:self.genderText.text forKey:@"gender"];
    [userDefault setObject:self.hobbyText.text forKey:@"hobby"];
//    [userDefault setObject:self.iconImg forKey:@"headimage"];
    [userDefault setObject:self.occupationText.text forKey:@"occupation"];
    [userDefault setObject:self.persignatureText.text forKey:@"persignature"];
    [userDefault setObject:self.locationText.text forKey:@"location"];
    [userDefault synchronize];
//    [SVProgressHUD showSuccessWithStatus:@"保存成功"];
    [SPHUDUtil showHUDWithDismissTimeInterval:0.5 message:@"保存成功" hudType:SPHUDTypeSuccess];
    [self.view endEditing:YES];
}

- (void)viewAppearWithPickerView:(UIPickerView *)pickerView{
    // ------全屏遮罩
    self.BGView                 = [[UIView alloc] init];
    self.BGView.frame           = [[UIScreen mainScreen] bounds];
    self.BGView.tag             = 100;
    self.BGView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.0];
    self.BGView.opaque = NO;
    
    //--UIWindow的优先级最高，Window包含了所有视图，在这之上添加视图，可以保证添加在最上面
    UIWindow *appWindow = [[UIApplication sharedApplication] keyWindow];
    [appWindow addSubview:self.BGView];
    
    // ------给全屏遮罩添加的点击事件
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(exitClick)];
    gesture.numberOfTapsRequired = 1;
    gesture.cancelsTouchesInView = NO;
    [self.BGView addGestureRecognizer:gesture];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.BGView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
        
    }];
    
    // ------底部弹出的View
    self.bottomView                 = [[UIView alloc] init];
    self.bottomView.frame           = CGRectMake(0, SCREEN_WIDTH + 50, SCREEN_WIDTH, SCREEN_WIDTH + 20 );
    self.bottomView.backgroundColor = [UIColor whiteColor];
    [self.bottomView addSubview:pickerView];
    [appWindow addSubview:self.bottomView];
    
    // ------View出现动画
    self.bottomView.transform = CGAffineTransformMakeTranslation(0.01, SCREEN_HEIGHT + 50);
    [UIView animateWithDuration:0.3 animations:^{
        
        self.bottomView.transform = CGAffineTransformMakeTranslation(0.01, 0.01);
        
    }];
}

/**
 * 功能： View退出
 */
- (void)exitClick {
    
    NSLog(@"====");
    [UIView animateWithDuration:0.3 animations:^{
        
        self.bottomView.transform = CGAffineTransformMakeTranslation(0.01, SCREEN_HEIGHT + 50);
        self.bottomView.alpha = 0.2;
        self.BGView.alpha = 0;
        
    } completion:^(BOOL finished) {
        
        [self.BGView removeFromSuperview];
        [self.bottomView removeFromSuperview];
    }];
    
}

- (void)setPicker{
    //性别
    self.sexPicker = [[UIPickerView alloc]initWithFrame:CGRectMake(0, -40, SCREEN_WIDTH, SCREEN_WIDTH )];
    self.sexPicker.delegate = self;
    self.sexPicker.dataSource = self;
    self.sexArr = [NSArray arrayWithObjects:@"男",@"女", nil];
    //年龄
    self.agePicker = [[UIPickerView alloc]initWithFrame:CGRectMake(0, -40, SCREEN_WIDTH, SCREEN_WIDTH )];
    self.agePicker.delegate = self;
    self.agePicker.dataSource = self;
    
    //爱好
    self.hobbyPicker = [[UIPickerView alloc]initWithFrame:CGRectMake(0, -40, SCREEN_WIDTH, SCREEN_WIDTH )];
    
    self.hobbyPicker.delegate = self;
    self.hobbyPicker.dataSource = self;
    //所在地
    self.locationPicker = [[UIPickerView alloc]initWithFrame:CGRectMake(0, -40, SCREEN_WIDTH, SCREEN_WIDTH )];
    self.locationPicker.delegate = self;
    self.locationPicker.dataSource = self;
    //职业
    self.occupationPicker = [[UIPickerView alloc]initWithFrame:CGRectMake(0, -40, SCREEN_WIDTH, SCREEN_WIDTH )];
    self.occupationPicker.delegate = self;
    self.occupationPicker.dataSource = self;
}

- (void)setBasicInfo{
    [self.iconImg sd_setImageWithURL:[NSURL URLWithString:self.userInfo.headimage] placeholderImage:[UIImage imageNamed:@"ha"]];
    [self.nameText setText:self.userInfo.nickname];
    [self.persignatureText setText:self.userInfo.persignature];
    [self.genderText setText:self.userInfo.gender];
    [self.ageText setText:self.userInfo.age];
    [self.hobbyText setText:self.userInfo.hobby];
    [self.locationText setText:self.userInfo.location];
    [self.occupationText setText:self.userInfo.occupation];
}
- (void)alertAction{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"选择相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"调用相册");
        [self photo:0];
    }];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"调用相机");
        [self photo:1];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    [alertVC addAction:photoAction];
    [alertVC addAction:cameraAction];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)photo:(NSInteger)index{
    UIImagePickerController *imgPicVC = [[UIImagePickerController alloc]init];
    switch (index) {
        case 0:
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                imgPicVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                imgPicVC.delegate = self;
                imgPicVC.allowsEditing = YES;
                [self presentViewController:imgPicVC animated:YES completion:nil];
            }
            break;
        case 1:
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                imgPicVC.sourceType = UIImagePickerControllerSourceTypeCamera;
                imgPicVC.delegate = self;
                imgPicVC.allowsEditing = YES;
                if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0f) {
                    imgPicVC.modalPresentationStyle = UIModalPresentationCurrentContext;
                }
                [self presentViewController:imgPicVC animated:YES completion:nil];
            }
            break;
        default:
            break;
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *img = info[UIImagePickerControllerOriginalImage];
    if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        [picker dismissViewControllerAnimated:YES completion:nil];
        [self.iconImg setImage:img];
    }else if (picker.sourceType == UIImagePickerControllerSourceTypeCamera){
        UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil);
        [picker dismissViewControllerAnimated:YES completion:nil];
        [self.iconImg setImage:img];
    }
    
}
#pragma  mark - UIPickerViewDelegate && UIPickerViewDatasource -
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (pickerView == self.sexPicker) {
        return 2;
    }else if (pickerView == self.agePicker){
        return self.ageArr.count;
    }else if (pickerView == self.hobbyPicker){
        return self.hobbyArr.count;
    }else if (pickerView == self.locationPicker){
        return self.locationArr.count;
    }else if (pickerView == self.occupationPicker){
        return self.occupationArr.count;
    }
    return 0;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (pickerView == self.sexPicker) {
        return self.sexArr[row];
    }else if (pickerView == self.agePicker){
        return self.ageArr[row];
    }else if (pickerView == self.hobbyPicker){
        return self.hobbyArr[row];
    }else if (pickerView == self.locationPicker){
        return self.locationArr[row];
    }else if (pickerView == self.occupationPicker){
        return self.occupationArr[row];
    }
    return nil;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (pickerView == self.sexPicker) {
        NSString *sex = self.sexArr[row];
        self.genderText.text = sex;
    }else if (pickerView == self.agePicker){
        NSString *age = self.ageArr[row];
        self.ageText.text = age;
    }else if (pickerView == self.hobbyPicker){
        NSString *hobby = self.hobbyArr[row];
        self.hobbyText.text = hobby;
    }else if (pickerView == self.locationPicker){
        NSString *location = self.locationArr[row];
        self.locationText.text = location;
    }else if (pickerView == self.occupationPicker){
        NSString *location = self.occupationArr[row];
        self.occupationText.text = location;
    }
    
}

#pragma mark - Button Change -
- (IBAction)changeSex:(UIButton *)sender {
    [self viewAppearWithPickerView:self.sexPicker];
}
- (IBAction)changeAge:(UIButton *)sender {
    [self viewAppearWithPickerView:self.agePicker];
}
- (IBAction)changeHobby:(UIButton *)sender {
    [self viewAppearWithPickerView:self.hobbyPicker];
}
- (IBAction)changeLocation:(UIButton *)sender {
    [self viewAppearWithPickerView:self.locationPicker];
}
- (IBAction)changeOccupation:(UIButton *)sender {
    [self viewAppearWithPickerView:self.occupationPicker];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end
